package com.example.wificollector;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import com.example.wificollector.entities.Position;
import com.example.wificollector.entities.SessionTrace;
import com.example.wificollector.entities.WifiTrace;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;

class WifiReceiver extends BroadcastReceiver {

	private WifiManager mainWifi;
	private Activity activity;
	private int counter;
	private int size;
	private int index = 0;
	private int outlierThreshold;
	private Position position;
	private ArrayList<SessionTrace>  sessionTraces;
	private Timer t;

	public WifiReceiver(Activity activity) {
		mainWifi = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE);
		this.activity = activity;
		sessionTraces = new ArrayList<SessionTrace>();
	}

	public void setScanTimer(int miliseconds) {
		t = new Timer();
		t.scheduleAtFixedRate(new TimerTask() {
			WifiManager mainWifi = (WifiManager) activity.getSystemService(Context.WIFI_SERVICE);

			@Override
			public void run() {
				mainWifi.startScan();
			}

		}, 0, miliseconds);
	}

	public void setCounter(int size) {
		this.size = size;
	}

	public void setPosition(int x, int y) {
		position = new Position();
		position.setX(x);
		position.setY(y);
	}

	public void onReceive(Context c, Intent intent) {

		if(size > 0)
		{
			List<ScanResult> scanResults = mainWifi.getScanResults();

			Parser parser = new Parser();
			SessionTrace sessionTrace = parser.parseToSessionTrace(scanResults, position);
			sessionTraces.add(sessionTrace);
			size--;
		}
	
		if (size <= 0) {
			try {
				stopCollecting();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				Log.e("Exception", "File write failed: " + e.toString());
				Toast.makeText(activity.getApplicationContext(), "File write failed: " + e.toString(), Toast.LENGTH_SHORT).show();
			}
		}
	}

	private void stopCollecting() throws IOException {
		t.cancel();
		
		WifiTrace wifiTrace = new WifiTrace();
		wifiTrace.setSessionTrace(sessionTraces);
		
		Gson gson = new GsonBuilder().create();
		String jsonObject = gson.toJson(wifiTrace);
		String fileName = "Position-" + position.getX() + "-" + position.getY()+".json";
		
		writeToSDFile(fileName, jsonObject);
		
		Intent replyIntent = new Intent("stopCollecting");
		activity.sendBroadcast(replyIntent);
	}
	
	private void writeToSDFile(String filename, String fileData) throws IOException{
		if(isExternalStorageWritable() == true)
		{
		    File dir = new File (Environment.getExternalStorageDirectory().toString() + "/IndoorPositioning/Measurements/");
		    dir.mkdirs();
		    File file = new File(dir + "/" + filename);
		    
		    FileOutputStream fOut = new FileOutputStream(file);
		    OutputStreamWriter osw = new OutputStreamWriter(fOut);
		    osw.write(fileData);
		    osw.flush();
		    osw.close();
		    Toast.makeText(activity.getApplicationContext(), "Wifi data saved!", Toast.LENGTH_SHORT).show();
		}
	}
	
	private boolean isExternalStorageWritable() {
	    String state = Environment.getExternalStorageState();
	    if (Environment.MEDIA_MOUNTED.equals(state)) {
	        return true;
	    }
	    return false;
	}
}
